"use strict";

const semver = require("semver");
const constant = require("./const");
const colors = require("colors/safe");
const log = require("@zreact-cli/log");
const { isObject } = require("@zreact-cli/utils");

class Command {
  constructor(argv) {
    if (!argv) {
      throw new Error("参数不能为空");
    }
    if (!Array.isArray(argv)) {
      throw new Error("参数不是数组");
    }
    if (argv.length < 1) {
      throw new Error("参数列表不能为空");
    }
    // console.log("command constructor", argv);
    this._argv = argv;
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      //检查node版本
      chain = chain.then(() => this.checkNodeVersion());
      chain = chain.then(() => this.initArgvs());
      chain = chain.then(() => this.init());
      chain = chain.then(() => this.exec());
      //初始化参数
      chain.catch((err) => log.error(err.message));
    });
  }
  //查看当前node环境
  checkNodeVersion() {
    //1 获取当前版本号
    const currentVersion = process.version;
    //2 比对版本号
    const lowestVerson = constant.LOWEST_NODE_VERSION;
    if (!semver.gte(currentVersion, lowestVerson)) {
      throw new Error(colors.red(`最低需要${lowestVerson}版本的node`));
    }
  }

  initArgvs(argv) {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }

  init() {
    throw new Error("init方法必须实现");
  }
  exec() {
    throw new Error("exec方法必须实现");
  }
}

module.exports = Command;
